package com.yuncool.controller.v1;

import com.yuncool.ApiMessage;
import com.yuncool.CommonUtils;
import com.yuncool.ServiceResult;
import com.yuncool.constants.RabbitQueue;
import com.yuncool.constants.ResultCode;
import com.yuncool.domain.CommonTag;
import com.yuncool.domain.vo.EmailRequestCodeVO;
import com.yuncool.domain.vo.SmsRequestVO;
import com.yuncool.service.CommonTagService;
import com.yuncool.service.EmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("common")
@Slf4j
@Api(tags = "公共接口")
public class CommonController {

	@Autowired
	RabbitTemplate rabbitTemplate;

	@Autowired
	EmailService emailService;

	@Autowired
	CommonTagService commonTagService;

	@ApiOperation(value = "短信发送接口", httpMethod = "POST")
	@PostMapping("sendSms")
	public ServiceResult<Boolean> sendSms(@RequestBody SmsRequestVO smsRequestVO, HttpServletRequest request) throws IOException {
		ServiceResult<Boolean> result = new ServiceResult<>();
		String ip = CommonUtils.getRemoteHost(request);
		smsRequestVO.setIp(ip);
		rabbitTemplate.convertAndSend(RabbitQueue.SMS_CODE, smsRequestVO);
		return result;
	}

	@ApiOperation(value = "邮件发送接口", httpMethod = "POST")
	@PostMapping("sendEmail")
	public ServiceResult<Boolean> sendEmail(@RequestBody EmailRequestCodeVO emailRequestCodeVO, HttpServletRequest request) throws IOException {
		ServiceResult<Boolean> result = new ServiceResult<>();
		String ip = CommonUtils.getRemoteHost(request);
		emailRequestCodeVO.setIp(ip);
		rabbitTemplate.convertAndSend(RabbitQueue.MAIL_QUEUE_CODE, emailRequestCodeVO);
		emailService.saveRecord(emailRequestCodeVO);
		return result;
	}

	@ApiOperation(value = "获取标签列表接口", httpMethod = "POST")
	@PostMapping("listCommonTag")
	public ServiceResult<List<CommonTag>> listCommonTag(@ApiParam(value = "父Id") String parentId) {
		ServiceResult<List<CommonTag>> result = new ServiceResult<>();
		try {
			result.setResultData(commonTagService.listCommonTag(parentId));
		} catch (Exception e) {
			e.printStackTrace();
			result.setError(ResultCode.REQUEST_ERROR, ApiMessage.getMessage("MSG001"));
		}
		return result;
	}
}
